﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class QuizPage : PhoneApplicationPage
    {
        private DetailMatkul detMatkul;
        private Quiz selectedQuiz;

        public QuizPage()
        {
            InitializeComponent();
            detMatkul = null;
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.DETMATKUL))
            {
                detMatkul = (DetailMatkul)PhoneApplicationService.Current.State[Config.DETMATKUL];
            }
            if (detMatkul == null)
            {
                detMatkul = new DetailMatkul();
                detMatkul.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            }

            LoadQuizList();
            ManageButton(selectedQuiz);
        }

        private void LoadQuizList()
        {
            listQuiz.ItemsSource = null;
            selectedQuiz = null;

            string url = string.Format("{0}&{1}", Config.Instance.QUIZ_SERVICE_URL() + Config.VIEW_ACTION_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(detMatkul);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listQuiz_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void listQuiz_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                QuizList list = JsonConvert.DeserializeObject<QuizList>(e.Result);
                if (list.Count > 0)                
                    listQuiz.ItemsSource = list;                
                else
                    listQuiz.ItemsSource = null;                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DeleteCurrentQuiz()
        {
            string json = null, url = null;

            if (selectedQuiz != null)
            {
                url = Config.Instance.QUIZ_SERVICE_URL() + Config.DELETE_ACTION_KEY;
                json = JsonConvert.SerializeObject(selectedQuiz);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                client.UploadStringCompleted += new UploadStringCompletedEventHandler(deleteQuiz_UploadStringCompleted);

                try
                {
                    client.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }
            }
        }

        private void deleteQuiz_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("Success"))
                    LoadQuizList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void listQuiz_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                selectedQuiz = (Quiz)e.AddedItems[0];

                if (selectedQuiz != null)
                {
                    pivotQuiz.SelectedIndex = 1;
                    textBoxCreated.Text = selectedQuiz.Awal.ToString("D");
                    textBoxBatas.Text = selectedQuiz.Akhir.ToString("D");
                    textBoxJam.Text = selectedQuiz.Mulai.Value.ToString("t") + " - " + selectedQuiz.Selesai.Value.ToString("t");
                    textBoxWaktu.Text = Convert.ToString(selectedQuiz.Waktu) + " menit";
                    textBoxJumlah.Text = Convert.ToString(selectedQuiz.Jumlah) + " soal";
                }

                ManageButton(selectedQuiz);
            }
        }

        private void addButton_Click(object sender, System.EventArgs e)
        {
            Quiz quiz = new Quiz();
            quiz.DetMatkul = detMatkul;

            Utility.GotoPage(this, "/View/Dosen/QuizFormPage.xaml");
            PhoneApplicationService.Current.State[Config.QUIZ] = quiz;
        }

        private void editButton_Click(object sender, System.EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/QuizFormPage.xaml");
            PhoneApplicationService.Current.State[Config.QUIZ] = selectedQuiz;
        }

        private void soalButton_Click(object sender, EventArgs e)
        {
            if (selectedQuiz == null)
            {
                MessageBox.Show("Pilih salah satu quiz!");
            }
            else
            {
                Utility.GotoPage(this, "/View/Dosen/QuestionQuizPage.xaml");
                PhoneApplicationService.Current.State[Config.QUIZ] = selectedQuiz;
            }
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            LoadQuizList();
            ManageButton(selectedQuiz);
        }

        private void ManageButton(Quiz quiz)
        {
            if (quiz != null)
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = true;
            }
            else
            {
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
                pivotQuiz.SelectedIndex = 0;
            }
        }

        private void contexSoal_Click(object sender, RoutedEventArgs e)
        {
            selectedQuiz = ((MenuItem)sender).CommandParameter as Quiz;
            if (selectedQuiz == null)
            {
                MessageBox.Show("Pilih salah satu quiz!");
            }
            else
            {
                Utility.GotoPage(this, "/View/Dosen/QuestionQuizPage.xaml");
                PhoneApplicationService.Current.State[Config.QUIZ] = selectedQuiz;
            }
        }

        private void menuRemove_Click(object sender, EventArgs e)
        {
            if (selectedQuiz == null)
            {
                MessageBox.Show("Pilih salah satu quiz!");
            }
            else
            {
                if (MessageBox.Show("Remove " + selectedQuiz.Nama + "?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    DeleteCurrentQuiz();
            }
        }

        private void pivotQuiz_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (selectedQuiz == null)
            {
                textBoxCreated.Text = "";
                textBoxBatas.Text = "";
                textBoxJumlah.Text = "";
                textBoxWaktu.Text = "";
            }
        }
    }
}